package com.JavaNet.chapter8_client_socket.full_quplex;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.net.*;
import javax.swing.*;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-20
 */
@Deprecated
public class MyClient3 extends JFrame implements ActionListener,KeyListener{

    JTextArea jta= null;
    JTextField jtf= null;
    JButton jb= null;
    JScrollPane jsp=null;

    JPanel jp1= null;

    //把信息发送给客户端的对象
    PrintWriter pw= null;

    public static void main(String[] args) {
        MyClient3 mc3= new MyClient3();
    }

    public MyClient3(){
        jta= new JTextArea();
        jsp= new JScrollPane(jta);
        jtf= new JTextField(15);
        jb= new JButton("发送");
        jb.addActionListener(this);

        jp1= new JPanel();
        jp1.add(jtf);
        jp1.add(jb);
        this.add(jsp, "Center");
        this.add(jp1, "South");
        this.setTitle("QQ聊天-客户端");
        this.setSize(320, 240);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        try {
            Socket s= new Socket("127.0.0.1", 9988);

            InputStreamReader isr= new InputStreamReader(s.getInputStream());
            BufferedReader br= new BufferedReader(isr);

            pw= new PrintWriter(s.getOutputStream(),true);

            while(true){
                //不停的读取从服务器端发来的信息
                String info= br.readLine();
                jta.append("服务器说:"+info+"\r\n");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        //如果用户按下按发送信的按钮
        if(arg0.getSource()==jb){

            String info= jtf.getText();
            //把客户端发送的信息显示在jta
            jta.append("客户端说："+info+"\r\n");

            pw.print(info);
            //清空输入框内容
            jtf.setText("");
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        if(e.getSource()==jtf){
            //System.out.println(e.getKeyCode());
            if(e.getKeyCode()==KeyEvent.VK_ENTER){
                String info=jtf.getText();
                jta.append("客户端说："+info+"\r\n");
                pw.println(info);
                //清空内存
                jtf.setText("");
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}
